<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="close">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="roleIds">
      <!-- 选项 -->
      <el-checkbox
        v-for="item in list"
        :key="item.id"
        :label="item.id"
      >
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assiginRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      list: [],
      roleIds: [],
      page: 1
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 关闭弹窗
    close () {
      this.roleIds = [] // 清空原来的数组
      this.$emit('update:showRoleDialog', false)
    },
    // TAG 获取所有的角色列表
    async getRoleList () {
      const data = await getRoleList({
        page: this.page,
        size: 10
      })
      this.list = data.rows
      if (data.rows.length) {
        this.page++
      }
    },
    // TAG 获取当前用户的角色
    async getUserDetailById (id) {
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds // 赋值本用户的角色
    },
    // 确定按钮
    async btnOk () {
      await assiginRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('更改成功')
      // 关闭窗口
      this.$emit('update:showRoleDialog', false)
    }

  }
}
</script>

